import os, sys

# 把包的父目录添加到系统搜索路径
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from base_data_structures.queue import Queue
import random

# 模拟打印队列, 计算平均等待时间
class Printer:
    '''
    打印机对象
    '''
    def __init__(self, ppm):
        self.pagerate = ppm # 打印速度
        self.currentTask = None # 打印任务
        self.timeRemaining = 0  # 任务倒计时

    def tick(self): # 打印1秒
        if self.currentTask != None:
            self.timeRemaining -= 1
            if self.timeRemaining <=0:
                self.currentTask = None

    def busy(self): # 打印机忙?
        if self.currentTask != None:
            return True
        else:
            return False

    def startNext(self, newTask):
        self.currentTask = newTask
        self.timeRemaining = newTask.getPages()*60/self.pagerate # 这样得到是作业打印几秒


class Task:
    def __init__(self, time):
        # 打印任务的时间戳
        self.timestamp = time 
        # 打印任务的页数
        self.pages = random.randrange(1, 21)

    def getStamp(self):
        return self.timestamp

    def getPages(self):
        return self.pages

    def waitTime(self, currentTime):
        return currentTime - self.timestamp


def newPrintTask():
    num = random.randrange(1, 181)
    if num == 180:
        return True
    else:
        return False

def simulation(numSecnds, pagesPerMinute):
    labPrinter = Printer(pagesPerMinute)
    printQueue = Queue()
    waitingTimes = []

    for currentSecond in range(numSecnds):
        if newPrintTask(): # 生成打印任务
            task = Task(currentSecond)
            printQueue.enqueue(task)
        if not labPrinter.busy() and not printQueue.isEmpty():
            nexttask = printQueue.dequeue()
            waitingTimes.append(nexttask.waitTime(currentSecond))
            labPrinter.startNext(nexttask)
        labPrinter.tick()

    averageWait = sum(waitingTimes)/ len(waitingTimes)
    print("Average Wait %6.2f secs %3d tasks remaining." % (averageWait, printQueue.size()))


for i in range(10):
    simulation(3600, 10)


